<?php
namespace app\api\controller;

use app\common\controller\Api;
use think\Exception;

class Upload extends Api {
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function upload(){
        try {
            // 获取上传文件
            $file = $this->request->file('file');
            if (!$file) {
                $this->error('请选择要上传的图片');
            }

            // 验证文件类型和大小
            $validate = [
                'size' => 10 * 1024 * 1024, // 10MB
                'ext'  => 'jpg,jpeg,png,gif,bmp,webp' // 允许的图片格式
            ];

            $info = $file->validate($validate)->move('./uploads');

            if (!$info) {
                $this->error($file->getError());
            }

            // 获取上传后的文件信息
            $saveName = $info->getSaveName();
            $filePath = '/uploads/' . str_replace('\\', '/', $saveName);

            // 返回完整的访问URL
            $domain = $this->request->domain();
            $imageUrl = $domain . $filePath;

            $this->success('上传成功', [
                'imgurl' => $imageUrl,
                'content' => $filePath
            ]);
        } catch (Exception $e) {
            $this->error('上传失败：' . $e->getMessage());
        }
    }


    public function newupload(){
        try {
            // 获取上传文件
            $file = $this->request->file('file');
            if (!$file) {
                $this->error('请选择要上传的文件');
            }

            // 获取文件MIME类型和扩展名
            $fileInfo = $file->getInfo();
            $mimeType = $fileInfo['type'];
            $extension = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));

            // 定义允许的文件类型
            $allowedTypes = [
                'image' => [
                    'mime' => ['image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp'],
                    'ext' => ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'],
                    'size' => 10 * 1024 * 1024 // 10MB
                ],
                'audio' => [
                    'mime' => ['audio/mpeg', 'audio/wav', 'audio/ogg', 'audio/aac', 'audio/flac', 'audio/mp4'],
                    'ext' => ['mp3', 'wav', 'ogg', 'aac', 'flac', 'm4a'],
                    'size' => 20 * 1024 * 1024 // 20MB
                ],
                'video' => [
                    'mime' => ['video/mp4', 'video/avi', 'video/quicktime', 'video/x-ms-wmv', 'video/x-flv', 'video/x-matroska', 'video/webm'],
                    'ext' => ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', '3gp'],
                    'size' => 100 * 1024 * 1024 // 100MB
                ]
            ];

            // 检测文件类型
            $fileType = null;
            foreach ($allowedTypes as $type => $rules) {
                if (in_array($mimeType, $rules['mime']) && in_array($extension, $rules['ext'])) {
                    $fileType = $type;
                    break;
                }
            }

            if (!$fileType) {
                $this->error('不支持的文件类型');
            }

            // 验证文件大小
            if ($fileInfo['size'] > $allowedTypes[$fileType]['size']) {
                $maxSize = $this->formatBytes($allowedTypes[$fileType]['size']);
                $this->error('文件大小不能超过 ' . $maxSize);
            }

            // 创建分类目录
            $uploadDir = './uploads/';
            $subDir = $fileType . 's/' . date('Ymd') . '/'; // images/20231201/
            $fullDir = $uploadDir . $subDir;

            // 确保目录存在
            if (!is_dir($fullDir)) {
                mkdir($fullDir, 0755, true);
            }

            $info = $file->move($fullDir);

            if (!$info) {
                $this->error($file->getError());
            }

            // 获取上传后的文件信息
            $saveName = $info->getSaveName();
            $filePath = '/uploads/' . $subDir . str_replace('\\', '/', $saveName);

            // 返回完整的访问URL
            $domain = $this->request->domain();
            $fileUrl = $domain . $filePath;

            $this->success('上传成功', [
                'url' => $fileUrl,
                'path' => $filePath,
                'name' => $info->getFilename(),
                'type' => $fileType,
                'size' => $info->getSize(),
                'size_format' => $this->formatBytes($info->getSize()),
                'extension' => $extension
            ]);

        } catch (Exception $e) {
            $this->error('上传失败：' . $e->getMessage());
        }
    }


    /**
     * 格式化文件大小
     */
    private function formatBytes($bytes, $precision = 2) {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];

        $bytes = max($bytes, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);

        $bytes /= pow(1024, $pow);

        return round($bytes, $precision) . ' ' . $units[$pow];
    }
}
